const replyMsg = {
    taskConfig: {},
    messageData: {},
    replayUserList: [],
    saveFileList: 0,
    viewList: [],
    saveFilePath: [],
    reply_group: [],
    initOtherData() {
        replyMsg.saveFileList = 0
        replyMsg.viewList = []
        if (replyMsg.saveFilePath.length) {
            replyMsg.saveFilePath.forEach((item) => {
                files.remove(item)
            })
            replyMsg.saveFilePath = []
        }
    },
    watchValue(key, newVal) {
        switch (key) {
            case 'taskStatus':
                if (newVal) {
                    replyMsg.initOtherData()
                    //当前回复任务已全部完成
                    console.log('replyMsg.replayUserList:' + JSON.stringify(replyMsg.replayUserList));
                    Xhs.taskConfig.taskStatus = true
                }
                break;
            case 'nowReplayIndex':
                replyMsg.initOtherData()
                let maxIndex = replyMsg.reply_group.length - 1
                let reply_group = replyMsg.reply_group[newVal]
                if (newVal > maxIndex) {
                    replyMsg.taskConfig.taskStatus = true
                    return
                    //已经执行完三个任务
                }
                sleep(1000)
                console.log('reply_group', reply_group);
                if (reply_group.image || reply_group.video) {
                    replyMsg.resolveMiddle(reply_group)
                }
                replyMsg.toOpenTask()
                break;
            case 'errorTask':
                if (newVal) {
                    let params = {
                        taskType: 'reply_msg',
                        taskName: '回复消息',
                        taskData: replyMsg.messageData,
                        errorTip: newVal,
                        taskDate: Comman.getDate()
                    }
                    Xhs.errorTask(params)
                    replyMsg.taskConfig.taskStatus = true
                }
                break;
            default:
                break;

        }
    },
    init(data) {
        replyMsg.initOtherData()
        replyMsg.messageData = data
        replyMsg.replayUserList = []
        //配置个消息任务随机参数
        replyMsg.reply_group[0] = data.setting.reply_group2 ? Comman.getRandomArrayItem(data.setting.reply_group2) : {}
        replyMsg.reply_group[1] = data.setting.reply_group1 ? Comman.getRandomArrayItem(data.setting.reply_group1) : {}
        replyMsg.reply_group[2] = data.setting.reply_group3 ? Comman.getRandomArrayItem(data.setting.reply_group3) : {}
        replyMsg.taskConfig = Comman.defineReactive(
            { taskStatus: false, errorTask: '', nowReplayIndex: 0 },
            '',
            replyMsg.watchValue
        )
        sleep(2000)
        replyMsg.taskConfig.nowReplayIndex = 0
    },
    start(data) {
        replyMsg.init(data)
    },

    toOpenTask() {
        console.log('FUNCTION: toOpenTask');
        let homeMnue = btnConfig.home.homeMnue
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back...');
            sleep(2000);
        }
        // 1.打开消息
        App.openBtn(3)
        //2.等待消息列表加载完成
        let messageList = btnConfig.message.messageHomeScroll.default()
        if (!messageList) {
            console.log('回复任务：获取私信列表失败');
            replyMsg.taskConfig.errorTask = '回复任务：获取私信列表失败'
            return
        }
        //3.下来刷新数据，更新最新
        gestures([350, [300, 400], [300, 1400]]);
        sleep(2000)
        // 置顶
        let messageHomeBtnMenu = btnConfig.message.messageHomeBtnMenu
        while (!depth(messageHomeBtnMenu.options.depth).id(messageHomeBtnMenu.options.id).exists()) {
            messageList.scrollBackward()
            sleep(2000)
        }
        switch (replyMsg.taskConfig.nowReplayIndex) {
            case 0:
                myUi.setTopText(Comman.getDate() + ': 私信回复任务：' + "任务执行中....")

                replyMsg.openSiXinTask()
                break;
            case 1:
                myUi.setTopText(Comman.getDate() + ': 点赞回复任务：' + "任务执行中....")
                replyMsg.openLikeTask()
                break;
            case 2:
                myUi.setTopText(Comman.getDate() + ': 关注回复任务：' + "任务执行中....")
                replyMsg.openFollowTask()
                break;
            default:
                break;
        }
    },
    openSiXinTask() {
        console.log('FUNCTION: openSiXinTask');
        let tip = text('不再提醒').findOne(2000)
        if (tip) {
            console.log('存在提示，点击关闭')
            App.clickByBtn(tip, 3)
        }
        let messageList = btnConfig.message.messageHomeScroll.default()
        let setting = {
            reply_group: replyMsg.reply_group[replyMsg.taskConfig.nowReplayIndex],
            reply_keyword: replyMsg.messageData.setting.reply_keyword2 || '',
        }
        let newItem = btnConfig.message.messageHomeItem.default()
        // 私信列表
        if (!newItem.length) {
            console.log('回复任务：无已私信数');
            // replyMsg.taskConfig.taskStatus = true
            replyMsg.taskConfig.nowReplayIndex += 1
            return
        }
        // 私信列表-未读私信
        let haveNews = newItem.findOne(id(btnConfig.message.messageHomeItemNews.options.id))
        if (!haveNews) {
            console.log('回复任务：无已私信数');
            // replyMsg.taskConfig.taskStatus = true
            replyMsg.taskConfig.nowReplayIndex += 1
            return
        }
        console.log('读到的私信', newItem.length);

        newItem.forEach((item) => {
            let isNews = item.findOne(id(btnConfig.message.messageHomeItemNews.options.id))
            let info = item.findOne(id(btnConfig.message.messageHomeItemInfo.options.id))
            // 存在未读私信，进行回复
            if (isNews) {
                let text = info.text()
                let findIndex = replyMsg.viewList.indexOf((view) => view == text)
                //未被回复的消息
                if (findIndex == -1) {
                    replyMsg.viewList.push(text)//记录已回复的消息
                    replyMsg.resolveNews(setting, item, text)
                }
            }
            sleep(500)
        })
        //翻页
        messageList.scrollForward()
        App.randomSleep()
        replyMsg.openSiXinTask()
    },
    openLikeTask() {
        console.log('FUNCTION: openLikeTask');
        let num = 0
        let newsBtn = btnConfig.message.messageHomeLikeBtn.default()
        //未查到有未读，重置后继续查询
        while (!newsBtn && num < 3) {
            gestures([350, [300, 400], [300, 1400]]);
            sleep(3000)
            newsBtn = btnConfig.message.messageHomeLikeBtn.default()
            num += 1
            sleep(3000)
        }
        if (!newsBtn && num >= 3) {
            console.log('回复任务：没有新回复消息');
            replyMsg.taskConfig.nowReplayIndex += 1
            return
        }
        if (newsBtn.bounds) {
            App.clickByBtn(newsBtn, 3)
        } else {
            App.click(btnConfig.message.messageHomeLikeBtn.position.x, btnConfig.message.messageHomeLikeBtn.position.y, 3)
        }
        replyMsg.likeFollowTask()
    },
    openFollowTask() {
        console.log('FUNCTION: openFollowTask');
        // 置顶
        let num = 0
        let messageHomeBtnMenu = btnConfig.message.messageHomeBtnMenu
        while (!depth(messageHomeBtnMenu.options.depth).id(messageHomeBtnMenu.options.id).exists()) {
            messageList.scrollBackward()
            sleep(2000)
        }
        let newsBtn = btnConfig.message.messageHomeFollowBtn.default()
        //未查到有未读，重置后继续查询
        while (!newsBtn && num < 3) {
            gestures([350, [300, 400], [300, 1400]]);
            sleep(3000)
            newsBtn = btnConfig.message.messageHomeFollowBtn.default()
            num += 1
            sleep(3000)
        }
        if (!newsBtn && num >= 3) {
            console.log('回复任务：没有新回复消息');
            // replyComment.taskConfig.taskStatus = true
            replyMsg.taskConfig.nowReplayIndex += 1
            return
        }
        if (newsBtn.bounds) {
            App.clickByBtn(newsBtn, 3)
        } else {
            App.click(btnConfig.message.messageHomeFollowBtn.position.x, btnConfig.message.messageHomeFollowBtn.position.y, 3)
        }
        replyMsg.likeFollowTask()
    },
    likeFollowTask() {
        console.log('FUNCTION: likeFollowTask');
        let tip = text('不再提醒').findOne(2000)
        if (tip) {
            console.log('存在提示，点击关闭')
            App.clickByBtn(tip, 3)
        }
        let nowReplayIndex = replyMsg.taskConfig.nowReplayIndex
        let setting = {
            reply_group: replyMsg.reply_group[nowReplayIndex],
            reply_keyword: ''
        }
        let scrollMessageList = btnConfig.message.messageAttScroll.default() //列表区域-自适应滚动
        let likeImgs = nowReplayIndex == 1 ? btnConfig.like.likeUserImg.default() : btnConfig.follow.followUserImg.default() //消息列表项
        let bottomDom = btnConfig.message.messageAttScrollbottom.default() || btnConfig.message.messageAttScrollbottom2.default()//底部控件
        let userName = nowReplayIndex == 1 ? btnConfig.like.likeUserName.default() : btnConfig.follow.followUserName.default()
        console.log('读到列表的用户', likeImgs.length);
        if (likeImgs.length) {
            likeImgs.forEach((element, index) => {
                let userNameText = userName[index].text()
                let findIndex = replyMsg.viewList.findIndex((view) => view == userNameText)
                console.log('当前遍历用户:', userNameText + '是否已被回复：' + findIndex);
                //未被回复的消息
                if (element.bounds && findIndex == -1) {
                    replyMsg.viewList.push(userNameText)
                    replyMsg.toSiXIng(element, setting)
                }
            });
        }
        if (bottomDom) {
            //触底，停止翻页
            replyMsg.taskConfig.nowReplayIndex += 1
            return
        }
        if (scrollMessageList.scrollForward()) {
            //未触底，继续翻页
            App.randomSleep()
            replyMsg.likeFollowTask()
        }
    },
    resolveMiddle(seed) {
        console.log('FUNCTION: resolveMiddle');
        let resource = []
        if (seed.image) {
            resource = seed.image.split(',')
        }
        if (seed.video) {
            resource.push(seed.video)
        }
        sleep(2000)
        if (resource.length) {
            myUi.setTopText(Comman.getDate() + ': 回复任务：' + "资源准备中....")
            let num = 0
            resource.forEach((item, index) => {
                let urlName = item.split('/').slice(-1)[0]
                if (!urlName) {
                    console.log('回复任务：文件解析名称失败：' + item);
                    return
                }
                let filePath = Xhs.resourcePath + new Date().getTime() + '_' + urlName
                let fileStatus = files.createWithDirs(filePath)
                let response = http.get(item);
                if (response.statusCode == 200) {
                    let fileBytes = response.body.bytes();
                    files.writeBytes(filePath, fileBytes);
                    media.scanFile(filePath);
                    replyMsg.saveFilePath.push(filePath)
                    num += 1
                    console.log('回复任务：文件下载完成：' + item + ' ---------NO：' + index);
                } else {
                    console.log('回复任务：文件解析名称失败' + response.statusCode);
                }
                sleep(500)
            })
            replyMsg.saveFileList = num
        }
        sleep(1000)
    },
    // 去点击私信
    toSiXIng(element, setting) {
        console.log('FUNCTION: toSiXIng');
        App.clickByBtn(element, true)
        sendMessageBtn = btnConfig.user.sendMessageBtn.default() || btnConfig.user.sendMessageBtnFollow.default()
        if (sendMessageBtn) {
            replyMsg.resolveNews(setting, sendMessageBtn, '')
        } else {
            console.log('未找到发送私信按钮')
        }
        App.randomSleep(2, 5)
        back()
    },
    //回复私信内容
    resolveNews(setting, item, info, getUserInfo) {
        console.log('FUNCTION: resolveNews');

        if (item.bounds) {
            App.clickByBtn(item, true)
        }
        // let messageItems = btnConfig.message.messageSiXinText.default()
        // if(!messageItems.length) {
        //     console.log('回复任务：未找到私信内容请检查--1');
        //     back()
        //     App.randomSleep()
        //     return;
        // }
        // let deviceLeft = device.width / 2
        //     // 区分用户和本人留言
        // let replayInfo = messageItems.filter(mess => mess.bounds().left < deviceLeft)
        // if(!replayInfo.length){
        //     console.log('回复任务：未找到私信内容请检查--2');
        //     back()
        //     App.randomSleep()
        //     return;
        // }
        // let newRrplayInfo = replayInfo[replayInfo.length-1].text()
        let searchKey = setting.reply_keyword
        let replyMessage = ''
        // console.log('newRrplayInfo',newRrplayInfo);

        // 判断是否回复内容是否包含关键字
        if (!info.includes(searchKey)) {
            console.log('回复任务：未找到关键字：' + searchKey + "仅收集用户信息");
            App.randomSleep(2, 5)
            replyMsg.getUserInfo(info, '')
        }
        if (info.includes(searchKey)) {
            //执行回复
            let addBtn = btnConfig.message.messageSiXinFile.default()
            if (!addBtn) {
                console.log('回复任务：未找到私信文件按钮，请检查');
                back()
                App.randomSleep()
                return;
            }
            if (addBtn.bounds) {
                App.clickByBtn(addBtn, true)
            } else {
                App.clickByBtn(btnConfig.message.messageSiXinFile.position.x, btnConfig.message.messageSiXinFile.position.y, true)
            }
            // 保持内容文本为空
            setText('')
            sleep(2000)
            if (setting.reply_group.content && setting.reply_group.content.length) {
                setting.reply_group.content.forEach((seed) => {
                    setText(seed)
                    sleep(2000)
                    let sendMessageBtn = btnConfig.message.sendMessageBtn.default()
                    if (!sendMessageBtn) {
                        console.log('回复任务：无法获取发送按钮，请检查')
                        setText('')
                    } else {
                        if (sendMessageBtn.bounds) {
                            App.clickByBtn(sendMessageBtn, true)
                        } else {
                            App.clickByBtn(btnConfig.message.sendMessageBtn.position.x, btnConfig.message.sendMessageBtn.position.y, true)
                        }
                        // if (!Xhs.isTest) {
                        // } else {
                        //     console.log('可以发送评论');
                        //     sleep(2000)
                        // }
                    }
                })
            }
            //图片文字分开发送
            if ((setting.reply_group.image || setting.reply_group.video) && replyMsg.saveFileList) {
                // resolveMiddle(seed)
                replyMsg.sendfile(setting.reply_group)
            }
            App.randomSleep(2, 5)
            replyMsg.getUserInfo(info, setting.reply_group)
        }
        App.randomSleep(2, 5)
        back()
    },
    sendfile() {
        let fileBtn = btnConfig.message.messageSiXinFileImg.default()
        if (fileBtn.bounds) {
            App.clickByBtn(fileBtn, true)
        } else {
            App.clickByBtn(btnConfig.message.messageSiXinFileImg.position.x, btnConfig.message.messageSiXinFileImg.position.y, true)
        }
        // 等待文件选择界面加载完成
        let messageFileMenu = btnConfig.file.messageFileMenu.default()
        if (!messageFileMenu) {
            console.log('回复任务：无法加载文件选择界面');
            return
        }
        let fileItem = btnConfig.file.messageFileImgRadio.default()
        if (!fileItem.length) {
            console.log('回复任务：无法获取文件列表');
            return
        }
        //遍历对应资源，选中它
        fileItem.forEach((file, index) => {
            if (index < replyMsg.saveFileList) {
                App.clickByBtn(file, 2)
            }
        })
        //发送
        let sendBtn = btnConfig.file.FileSend.default()
        if (!sendBtn) {
            console.log('回复任务：无法获取发送按钮');
            back()
            return;
        }
        console.log('文件下载总数', replyMsg.saveFileList);
        if (sendBtn.bounds) {
            App.clickByBtn(sendBtn, 3)
        } else {
            App.clickByBtn(btnConfig.file.FileSend.position.x, btnConfig.file.FileSend.position.y, 3)
        }
        
        // if (!Xhs.isTest) {
        // } else {
        //     console.log('可以发送文件');
        //     sleep(2000)
        //     back()
        // }

    },
    getUserInfo(info, reply_group) {
        let userImgBtn = btnConfig.message.messageSiXinUserImg.default()
        if (userImgBtn) {
            if (userImgBtn.bounds) {
                App.clickByBtn(userImgBtn, true)
            } else {
                App.clickByBtn(btnConfig.message.messageSiXinUserImg.position.x, btnConfig.message.messageSiXinUserImg.position.y, true)
            }
            let userId = btnConfig.user.userPageId.default()
            let userLocation = btnConfig.user.userPageLocation.default()
            let userNick = btnConfig.user.userPageNick.default()
            let follow = btnConfig.user.userPagefollow.default()
            let fans = btnConfig.user.userPagefans.default()
            let like = btnConfig.user.userPagelike.default()
            let gender = btnConfig.user.userPageGender.default()
            let deal_content = reply_group ? JSON.stringify(reply_group) : ''
            if (userId) {
                let userInfo = {
                    like_num: like ? like.desc().replace('获赞与收藏', '') : 0,
                    fans_num: fans ? fans.desc().replace('粉丝', '') : 0,
                    follow_num: follow ? follow.desc().replace('关注', '') : 0,
                    gender: gender ? gender.desc().replace(',', '') : '',
                    xhsid: userId.text().replace('小红书号：', ''),
                    nickname: userNick ? userNick.text() : '',
                    avatar: "",
                    ip: userLocation ? userLocation.text().replace('IP属地：', '') : '',
                    msg_type: "reply_comment",
                    content: info, deal_content: deal_content
                }
                console.log('userInfo', userInfo);

                replyMsg.replayUserList.push(userInfo)
            } else {
                console.log('回复任务：报错--无法获取用户信息');
            }
            sleep(2000)
            back()
        } else {
            console.log('回复任务：报错--userImgBtn');
        }
        sleep(2000)
    }
}
module.exports = replyMsg